<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>字典管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
  <link rel="stylesheet" href="../css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
  <div class="layuimini-main">

    <fieldset class="table-search-fieldset">
      <legend>搜索信息</legend>
      <div style="margin: 10px 10px 10px 10px">
        <form class="layui-form layui-form-pane" action="">
          <div class="layui-form-item">
            <div class="layui-inline">
              <label class="layui-form-label">字典名称</label>
              <div class="layui-input-inline">
                <input type="text" name="dictName" class="layui-input">
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">字典编号</label>
              <div class="layui-input-inline">
                <input type="text" name="dictCode" class="layui-input">
              </div>
            </div>
            <div class="layui-inline">
              <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
              <button type="button" class="layui-btn layui-btn-normal"  id="data-reset-btn"><i class="layui-icon layui-icon-refresh"></i> 重 置</button>
            </div>
          </div>
        </form>
      </div>
    </fieldset>

    <script type="text/html" id="toolbarDemo">
      <div class="layui-btn-container">
        <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
        <button class="layui-btn layui-btn-danger layui-btn-sm data-delete-btn" lay-event="deleteBatch"> 批量删除 </button>
      </div>
    </script>

    <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

    <script type="text/html" id="currentTableBar">
      <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
      <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="config">字典配置</a>
      <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
    </script>

    <!-- 添加页面 -->
    <div id="add" style="display: none">
      <div class="layui-form layuimini-form" lay-filter="addForm">
        <div class="layui-form-item">
          <label class="layui-form-label required">字典名称</label>
          <div class="layui-input-inline">
            <input type="text" name="dictName" lay-verify="required" lay-reqtext="字典名称不能为空"
                   placeholder="请输入字典名称" value="" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">字典编号</label>
          <div class="layui-input-inline">
            <input type="text" name="dictCode" lay-verify="required" lay-reqtext="字典编号不能为空"
                   placeholder="请输入字典编号" value="" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">描述</label>
          <div class="layui-input-inline">
            <input type="text" name="description" placeholder="请输入描述" value="" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">状态</label>
          <div class="layui-input-inline">
            <input type="text" name="delFlag" placeholder="请输入状态 0-正常 1-已删除" value="" class="layui-input">
          </div>
        </div>

        <div class="layui-form-item">
          <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveAddBtn">确认保存</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑页面 -->
    <div id="edit" style="display: none">
      <div class="layui-form layuimini-form" lay-filter="editForm">
        <div class="layui-form-item">
          <label class="layui-form-label required">序号</label>
          <div class="layui-input-inline">
            <input type="text" name="id" readonly class="layui-input layui-disabled">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">字典名称</label>
          <div class="layui-input-inline">
            <input type="text" name="dictName" lay-verify="required" lay-reqtext="字典名称不能为空"
                   placeholder="请输入字典名称" value="" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">字典编号</label>
          <div class="layui-input-inline">
            <input type="text" name="dictCode" lay-verify="required" lay-reqtext="字典编号不能为空"
                   placeholder="请输入字典编号" value="" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">描述</label>
          <div class="layui-input-inline">
            <input type="text" name="description" placeholder="请输入描述" value="" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveEditBtn">确认保存</button>
          </div>
        </div>
      </div>
    </div>

  </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
  layui.use(['form', 'table', 'layer'], function () {
    var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layer = layui.layer;

    var index;

    // 初始化表格
    table.render({
      elem: '#currentTableId',
      url: '/sysDict/queryPage',
      parseData: function (res) {
        return {
          "code": res.code,
          "msg": res.msg,
          "count": res.data.total,
          "data": res.data.list
        };
      },
      toolbar: '#toolbarDemo',
      cols: [[
        {type: "checkbox", width: 50},
        {field: 'id', width: 180, title: '序号', sort: true},
        {field: 'dictName', width: 200, title: '字典名称'},
        {field: 'dictCode', width: 200, title: '字典编号'},
        {field: 'description', width: 200, title: '描述'},
        {title: '操作', minWidth: 240, toolbar: '#currentTableBar', align: "center"}
      ]],
      limits: [5, 10, 50, 100],
      limit: 10,
      page: true,
      skin: 'line'
    });

    // 搜索监听
    form.on('submit(data-search-btn)', function (data) {
      table.reload('currentTableId', {
        page: { curr: 1 },
        where: data.field
      }, 'data');
      return false;
    });

    // 重置按钮点击事件
    $('#data-reset-btn').on('click', function () {
      // 1. 清空输入框内容
      $('input[name="dictName"]').val('');
      $('input[name="dictCode"]').val('');

      // 2. 强制刷新表格，跳回第一页，并清空所有查询参数
      table.reload('currentTableId', {
        page: { curr: 1 },         // 回到第一页
        where: {}                  // 不带任何查询参数（相当于重载原始数据）
      });
    });


    // 工具栏监听
    table.on('toolbar(currentTableFilter)', function (obj) {
      if (obj.event === 'add') {
        form.val("addForm", {}); // 清空添加表单
        index = layer.open({
          title: '添加字典信息',
          type: 1,
          shade: 0.2,
          maxmin: true,
          shadeClose: true,
          area: ['75%', '75%'],
          content: $('#add'),
        });
        $(window).on("resize", function () {
          layer.full(index);
        });
      }else if (obj.event === 'deleteBatch') {
        var checkStatus = table.checkStatus(obj.config.id);
        var data = checkStatus.data;

        if (data.length === 0) {
          layer.msg("请选择要删除的数据");
          return;
        }

        let ids = data.map(function(item) { return item.id; });

        $.ajax({
          url: '/sysDict/deleteBatch',
          type: 'GET',
          data: {
            ids: ids.join(',')
          },
          success: function(res) {
            if (res.code === 0) {
              layer.msg("删除成功");
              table.reload('currentTableId');
            } else {
              if (res.data && res.data.length > 0) {
                showDictItems(res.data);
              } else {
                layer.msg("删除失败：" + res.msg || "未知错误");
              }
            }
          },
          error: function() {
            layer.msg("请求失败，请检查网络");
          }
        });
      }

    });

    // 表格行操作监听
    table.on('tool(currentTableFilter)', function (obj) {
      var data = obj.data;
      if (obj.event === 'edit') {
        form.val("editForm", data); // 填入编辑数据
        index = layer.open({
          title: '编辑字典',
          type: 1,
          shade: 0.2,
          maxmin: true,
          shadeClose: true,
          area: ['75%', '75%'],
          content: $('#edit'),
        });
        $(window).on("resize", function () {
          layer.full(index);
        });
      } else if (obj.event === 'delete') {
        $.getJSON('/sysDict/delete?id=' + data.id, function (res) {
          if (res.code === 0) {
            layer.msg("删除成功");
            obj.del();
          } else {
            if (res.data && res.data.length > 0) {
              showDictItems(res.data);
            } else {
              layer.msg("删除失败：" + res.msg || "未知错误");
            }
          }
        });
      }else if (obj.event === 'config') {
        // 配置按钮点击事件
        layer.open({
          title: '字典配置',
          type: 2,
          shade: 0.2,
          maxmin: true,
          shadeClose: true,
          area: ['80%', '80%'],
          content: '/view/dictItem.html?id=' + data.id // 修改为跳转到 dictItem.html 页面
        });
      }
    });

    // 添加提交
    form.on('submit(saveAddBtn)', function (data) {
      $.post("/sysDict/add", data.field, function (res) {
        if (res.code === 0) {
          layer.msg("添加成功");
          table.reload('currentTableId');
        } else {
          layer.msg("添加失败");
        }
        layer.close(index);
        //location.reload();
      }, "json");
      return false;
    });

    // 编辑提交
    form.on('submit(saveEditBtn)', function (data) {
      $.post("/sysDict/update", data.field, function (res) {
        if (res.code === 0) {
          layer.msg("修改成功");
          table.reload('currentTableId',{
            page: {
              curr: res.data.total % 10 === 0 ? res.data.total / 10 : Math.floor(res.data.total / 10) + 1
            }
          });
        } else {
          layer.msg("修改失败");
        }
        layer.close(index);
        //location.reload();
      }, "json");
      return false;
    });

  });

  //在 JS 中添加一个弹窗函数用于展示字典配置项
  function showDictItems(items) {
    let html = "<table class='layui-table'><thead><tr><th>ID</th><th>字典项文本</th><th>字典项值</th></tr></thead><tbody>";
    items.forEach(function(item) {
      html += `<tr><td>${item.id}</td><td>${item.itemText}</td><td>${item.itemValue}</td></tr>`;
    });
    html += "</tbody></table>";

    layer.open({
      title: '警告：存在字典配置项',
      content: html,
      area: ['600px', '400px'],
      btn: ['确定'],
      yes: function(index) {
        layer.msg("请先删除以上字典配置项后再操作");
        layer.close(index);
      }
    });
  }

</script>

</body>
</html>
